package com.company.test30.CharSoftware;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.DataOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by v on 16-12-6.
 */
public class MyKeyListener extends KeyAdapter {
    private ChatPanel chatPanel;
    private DataOutputStream output;
    private String name;

    public MyKeyListener(ChatPanel chatPanel,
                         DataOutputStream output,String name){
        this.chatPanel=chatPanel;
        this.output=output;
        this.name=name;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        super.keyPressed(e);
        chatPanel.keys[e.getKeyCode()]=true;
        if(chatPanel.keys[KeyEvent.VK_CONTROL]
                &&chatPanel.keys[KeyEvent.VK_ENTER]){
            chatPanel.jtaInput.append("\n");
        }else if(chatPanel.keys[KeyEvent.VK_ENTER]){
            //若消息为空则不允许发送
            if(chatPanel.jtaInput.getText().equals("")){
                return;
            }

            String message=generateMessage(chatPanel.jtaInput.getText(),name);
            chatPanel.jtaShow.append(message);
            Thread thread=new Thread(new SendMessage(output,message));
            thread.start();
            thread=new Thread(new ClearMessage(chatPanel));
            thread.start();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        super.keyReleased(e);
        chatPanel.keys[e.getKeyCode()]=false;
    }

    //根据发送的消息，生成一个格式型消息
    public static String generateMessage(String message,String name){
        String generateMessage="";
        SimpleDateFormat date=new
                SimpleDateFormat("HH:mm:ss");
        generateMessage+=date.format(new Date())+"    ";
        generateMessage+=name+":\n";
        generateMessage+=message+"\n\n";

        return generateMessage;
    }
}
